const myRequest = require('../../tool/myRequest')
const tool = require('../../tool/tool')
const daoUser = require('../../dao/daoUser')
const cheerio = require('cheerio');

// 解析单本漫画的信息，并保存到数据库
function xxx(globalOption_ = {}, id = '', url = '', option = {}) {
  url = url || 'http://localhost:8422/pages/test.html';
  // url = url || 'https://manwast.cc/book/307992';
  // console.log(`id,url`, id, url)
  globalOption_.requestCount++;
  globalOption_.runCountNow++;
  return new Promise((resolve, reject) => {
    myRequest(url, {}).then(d => {
      if (d.status == 200) {
        let tt = {};
        const $ = cheerio.load(d.data);
        let aTags = $('.detail-main-info-title');
        if (aTags.length == 0) { console.log(`==*****=====没有找到对应的目标====***===1`,); reject(); return };

        // 获取名称
        tt['name_'] = removeEmojis(aTags.text().trim());

        // 获取类型
        let x = $('.detail-main-info-author')
        if (x.length == 0) { console.log(`==*****=====没有找到对应的目标====***===2`,); reject(); return };
        x.each(function () {
          t = $(this).find('.detail-main-info-author-field');
          v = $(this).find('.detail-main-info-value');
          if (t.length == 0) { console.log(`==*****=====没有找到对应的目标====***===3`,); reject(); return };
          t = t.text().trim().replace('：', '');
          v = v.text().trim();
          switch (t) {
            case '作者': tt['author'] = removeEmojis(v.replace(/\s+/g, '-')); break;
            case '更新状态': tt['status_'] = removeEmojis(v); break;
            case '最新章节': tt['new_chapter'] = removeEmojis(v); break;
            case '地区': tt['region'] = removeEmojis(v); break;
            case '类别': tt['type'] = removeEmojis(v); break;
            default: break;
          }
        });

        // 判断是否是更新book
        if (option.new_chapter && option.new_chapter == tt['new_chapter']) { console.log(`==*****===== ${id} Book还没有更新 ====***===7`,); reject(); return; }

        // 获取tag
        let tag = $('a.info-tag');
        if (tag.length > 0) {
          let ts = [];
          tag.each(function () {
            ts.push($(this).text().trim());
          })
          tt['tag'] = ts;
          if (globalOption_.tagas && tag.length > 0) {
            let tagsNum = [];
            ts.forEach(tsawef => {
              if (globalOption_.tagas[tsawef]) { tagsNum.push(globalOption_.tagas[tsawef]) }
            });
            tt['tag_2'] = tagsNum.join('|');
          }
        }
        else console.log(`==*****=====没有找到对应的目标====***===4`,);

        // 获取章节连接和标题
        let z = $('a.chapteritem ');
        if (z.length == 0) { console.log(`==*****=====没有找到对应的目标====***===5`,); reject(); return };
        let hrefs = []
        z.each(function () {
          let ttt = $(this).text().trim()
          ttt = removeEmojis(ttt);
          let h = $(this).attr('href')
          hrefs.push({ title: ttt, href: h });
        })
        tt['chapter'] = hrefs;

        // 获取图片
        let i = $('.detail-main-cover img.lazy');
        if (i.length == 0) { console.log(`==*****=====没有找到对应的目标====***===6`,); reject(); return };
        tt['img'] = i[0].attribs['data-original'];


        // 获取更新日期
        let update_date = $('.detail-list-title-3').text().trim();
        tt['update_date'] = tool.getDate(update_date);


        // let sql = []; // 注意了：这里的排序不能错了，需要和sql语句对应上顺序
        // sql.push(`id="${id}"`);
        // sql.push(`name_="${tt.name_}"`);
        // sql.push(`author="${tt.author}"`);
        // sql.push("status_=" + (tt.status_ == "连载中" ? 0 : 1));
        // sql.push(`new_chapter="${tt.new_chapter}"`);
        // sql.push(`type="${tt.type}"`);
        // sql.push(`region="${tt.region}"`);
        // sql.push(`is_updata_info=` + 1);
        // sql.push(`img="${tt.img}"`);
        // sql.push(`tag="${tt.tag_2 || ""}"`);
        // sql.push(`update_date="${tt.update_date || ""}"`);
        // sql = sql.join(",");

        // id && daoUser.updateBook([sql]).then(d => {
        //   // console.log(`d`, d)
        //   console.log(`updateBook ok`, `错误：`, globalOption_.errorcount, '请求总数：', globalOption_.requestCount, '成功总数：', globalOption_.successCount, '正在处理数：', globalOption_.runCountNow, id, url);
        //   resolve({});
        // }).catch(e => { console.log(`e1`, id, e); reject() })

        id && daoUser.updateBook2([`'${id}','${tt.name_}','${tt.author}',${tt.status_ == "连载中" ? 0 : 1},'${tt.new_chapter}','${tt.type}','${tt.region}',1,'${tt.img}','${tt.tag_2}','${tt.update_date}'`]).then(d => {
          // console.log(`d`, d)
          console.log(`updateBook ok`, `错误：`, globalOption_.errorcount, '请求总数：', globalOption_.requestCount, '成功总数：', globalOption_.successCount, '正在处理数：', globalOption_.runCountNow, id, url);
          resolve({});
        }).catch(e => { console.log(`e1`, id, e); reject() })

        // 保存章节连接和标题
        if (tt.chapter.length > 0 && id) {
          let ccs = [];
          tt.chapter.forEach((cc, nn) => {
            ccs.push(`('${id}_${nn}','${id}' , ${nn}, '${cc.href}',  '${cc.title}', 1)`)
          });
          ccs = ccs.join(',');
          // console.log(`ccs`, ccs)
          daoUser.addChapter([ccs]).then(d => {
            // console.log(`addChapter ok ==== `, id, url)
          }).catch(e => { console.log(`e5`, id, url, e); reject() })
        }

        // console.log(``, tt)
        // console.log(`sql = = = = = =  = `, sql)
      } else { console.log(`请求失败`, id, url, d.status); reject(); }
    }).catch(e => { console.log(`e2`, id, url, e); reject(); })
  })
}
// xxx()

// let tagas = {}
// let errorcount = 0;
// let requestCount = 0;
// let successCount = 0;
// let runCountNow = 0;
// let assObj = {};

let globalOption = {
  tagas: {},
  errorcount: 0,
  requestCount: 0,
  successCount: 0,
  runCountNow: 0,
  assObj: {},
}
let globalOption_1 = JSON.parse(JSON.stringify(globalOption));
let globalOption_2 = JSON.parse(JSON.stringify(globalOption));
let globalOption_3 = JSON.parse(JSON.stringify(globalOption));
let globalOption_4 = JSON.parse(JSON.stringify(globalOption));

let exportsObject = {
  xxx,
  run() {
    daoUser.getTags().then(d => {
      d.forEach(tg => { globalOption.tagas[tg.tag_title] = tg.tag_id; });
      let runCount = limit = 35;
      setInterval(() => {
        if (runCount > 0) {
          daoUser.getBooksFormIs_updata_infoLimit(globalOption.errorcount + globalOption.requestCount, limit).then(d => {
            // console.log(``, d)
            d.forEach(element => {
              if (runCount <= 0) return;
              runCount--;
              xxx(globalOption_1, element.id, element.base_url + element.url).then(() => {
                runCount++;
                globalOption.successCount++;
              }).catch(err => {
                runCount++;
                globalOption.errorcount++;
              })
              // xxx('', element.base_url + element.url);
              // xxx()
            });
          })
        }
      }, 5000);
    }).catch(e => console.log(`e3`, e))
  },
  run2() {
    daoUser.getTags().then(d => {
      d.forEach(tg => { globalOption.tagas[tg.tag_title] = tg.tag_id; });
      setInterval(() => {
        daoUser.getBooksFormIs_updata_infoLimit(globalOption.errorcount + globalOption.requestCount, 15).then(d => {
          d.forEach(element => {
            xxx(globalOption_2, element.id, element.base_url + element.url).then(() => {
              globalOption.successCount++;
              globalOption.runCountNow--;
            }).catch(err => {
              globalOption.errorcount++;
              globalOption.runCountNow--;
            })
          });
        })
      }, 1000 * 1);
    }).catch(e => console.log(`e3`, e))
  },
  run3() {
    daoUser.getTags().then(d => {
      d.forEach(tg => { globalOption.tagas[tg.tag_title] = tg.tag_id; });
      let index = 0;
      let runCount = 116;
      let darr = [];
      daoUser.getBooksFormIs_updata_infoLimit(globalOption.errorcount + globalOption.requestCount, 1000).then(d => {
        d.forEach(element => { darr.push(element); });
        console.log(`run3 - da`, darr.length)
        let lsdjfe = setInterval(() => {
          if (runCount > 0 && index < darr.length) {
            if (globalOption.assObj[darr[index].id]) { index++; return };
            globalOption.assObj[darr[index].id] = true;
            runCount--;
            xxx(globalOption_3, darr[index].id, darr[index].base_url + darr[index].url).then(() => {
              runCount++;
              globalOption.successCount++;
              globalOption.runCountNow--;
            }).catch(err => {
              globalOption.runCountNow--;
              runCount++;
              globalOption.errorcount++;
            })
            index++;
          }
          if (index == darr.length) {
            clearInterval(lsdjfe);
            globalOption.errorcount = globalOption.requestCount = 0;
            setTimeout(() => { exportsObject.run3(); }, 3000);
          }
        }, 50);
      })
    }).catch(e => console.log(`e3`, e))
  },
  // 更新半年内连载的
  updateBookOfUpdate_date() {
    daoUser.getTags().then(d => {
      d.forEach(tg => { globalOption.tagas[tg.tag_title] = tg.tag_id; });
      let index = 0;
      let runCount = 50;
      let darr = [];
      daoUser.getBooksForm_6_MONTH().then(d => {
        d.forEach(element => { darr.push(element); });
        console.log(`updateBookOfUpdate_date - da`, darr.length)
        let lsdjfe = setInterval(() => {
          if (runCount > 0 && index < darr.length) {
            runCount--;
            xxx(globalOption_4, darr[index].id, darr[index].base_url + darr[index].url, darr[index]).then(() => {
              runCount++;
              globalOption.successCount++;
              globalOption.runCountNow--;
            }).catch(err => {
              globalOption.runCountNow--;
              runCount++;
              globalOption.errorcount++;
            })
            index++;
          }
          // if (index == darr.length) { clearInterval(lsdjfe); setTimeout(() => { exportsObject.updateBookOfUpdate_date(); }, 3000); }
        }, 50);
      })
    }).catch(e => console.log(`e3`, e))
  }
}

module.exports = exportsObject;


// 去除其中 MySQL 不支持的表情图片或其他特殊字符（如 emoji）
function removeEmojis(str) {
  return str.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, '').replace(/['"]/g, '').replace(/\\/g, '');
}
